<?php
namespace app\api\controller\system;

use app\admin\model\Activity;
use app\admin\model\Consumer;
use app\admin\model\Coupon;
use app\admin\model\CouponOrder;
use app\admin\model\Order;
use app\admin\model\OrderLog;
use app\admin\model\Store;
use app\admin\model\StreamLog;
use app\admin\model\Ticket;
use app\admin\model\WriteLog;
use app\api\controller\consume\ConsumerClaimLog;
use think\App;
use think\facade\Db;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use Symfony\Component\VarDumper\Cloner\Data;
use app\admin\model\SystemUser;
use app\admin\model\SystemUserRole;
use app\admin\model\FigureUser;
use app\admin\model\FigurePartner;
use app\admin\model\FigureBalanceLog;
use app\admin\model\FigureMemberLog;
use app\admin\model\FigurePointLog;
use app\admin\model\FigureCardLog;
use app\admin\model\FigurePartnerLog;

/**
 * @ControllerAnnotation(title="用户")
 */
class User extends AdminController
{

    /**
     * 字段排序
     *
     * @var array
     */
    protected $sort = [
        'user_id' => 'desc'
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        
        $this->model = new \app\admin\model\SystemUser();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        $request = $this->request;
        $user_id = $request->_UID;
        try {
            
            $nickname = input("nickname");
            $phone = input("phone");
            $u_id = input("user_id");
            
            $has_past = input("has_past");
            $past_data = input("past_data");
            
            $create_time = input("create_time");
            
            $page = input("page");
            $limit = input("limit");
            
            $where[] = [
                "tenant_id",
                "=",
                1
            ];
            
            if (! empty($u_id)) {
                $where[] = [
                    "agency_id",
                    "=",
                    $u_id
                ];
            }
            
            if (! empty(input('nickname'))) {
                $where[] = [
                    "nickname",
                    "LIKE",
                    "%" . input('nickname') . "%"
                ];
            }
            
            if (! empty(input('phone'))) {
                $where[] = [
                    "phone",
                    "LIKE",
                    "%" . input('phone') . "%"
                ];
            }
            
            if (! empty($has_past)) {
                if ($has_past == 1) {
                    $where[] = [
                        "has_past",
                        "=",
                        $has_past
                    ];
                } else {
                    $where[] = [
                        "has_past",
                        "=",
                        $has_past
                    ];
                    if (! empty($past_data)) {
                        $where[] = [
                            "past_data",
                            ">=",
                            strtotime($past_data[0])
                        ];
                        $where[] = [
                            "past_data",
                            "<=",
                            strtotime($past_data[1])
                        ];
                    }
                }
            }
            
            if (! empty(input('createTimeStart'))) {
                $where[] = [
                    "create_time",
                    ">=",
                    strtotime(input('createTimeStart'))
                ];
            }
            
            if (! empty(input('createTimeEnd'))) {
                $where[] = [
                    "create_time",
                    "<=",
                    strtotime(input('createTimeEnd'))
                ];
            }
            
            $list = $this->model->where($where)
                ->field("*,user_id userId,create_time createTime,update_time updateTime,IF(sex=1,'男','女') sexName,DATE_FORMAT(FROM_UNIXTIME(past_data),'%Y-%m-%d') past_data")
                ->limit(($page - 1) * $limit, $limit)
                ->order($this->sort)
                ->select();
            
            foreach ($list as $key => $value) {
                
                $roles = SystemUserRole::alias('a')->leftJoin('wjyk_system_role b', 'a.role_id=b.role_id')
                    ->where("a.user_id = {$value['user_id']}")
                    ->field("b.role_id roleId,b.role_name roleName,b.role_code roleCode,b.tenant_id tenantId")
                    ->select();
                
                $roleIds = [];
                foreach ($roles as $k => $v) {
                    array_push($roleIds, $v['roleId']);
                }
                $list[$key]['roleIds'] = $roleIds;
                
                $list[$key]['roles'] = $roles;
                
                $list[$key]['createTime'] = $value['create_time'];
            }
            
            $count = $this->model->where($where)->count();
            
            return msg([
                'list' => $list,
                'count' => $count
            ], 0, "");
        } catch (\Throwable $th) {
            return msg([], 1, "获取数据失败 : " . $th->getMessage());
        }
    }

    /**
     * @NodeAnotation(title="查询代理最新信息")
     */
    public function queryInfo()
    {
        $request = $this->request;
        $user_id = $request->_UID;
        try {
            
            $user = $this->model->where("user_id", $user_id)->find();
            
            return msg($user, 0, "");
        } catch (\Throwable $th) {
            return msg([], 1, "获取数据失败 : " . $th->getMessage());
        }
    }

    /**
     * 添加管理账号
     * @NodeAnotation(title="添加管理账号")
     */
    public function add()
    {
        $request = $this->request;
        $user_id = $request->_UID;
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            
            Db::startTrans();
            try {
                // require "../vendor/phpqrcode/phpqrcode.php";
                // if (! empty($post['past_data'])) {
                // $post['past_data'] = strtotime($post['past_data']);
                // }
                $data = [
                    "nickname" => $post['nickname'],
                    "password" => $post['password'],
                    "phone" => $post['phone'],
                    "sex" => $post['sex'],
                    "username" => $post['username'],
                    'tenant_id' => $request->_TENANTID
                ];
                
                if ($request->_TENANTID == 2) {
                    $agencyUser = SystemUser::where('user_id', $user_id)->find();
                    $data['agency_domain'] = empty($agencyUser['agency_domain']) ? '' : $agencyUser['agency_domain'];
                }
                
                $roleIds = $post['roleIds'];
                
                unset($post['roles']);
                unset($post['roleIds']);
                
                $user = SystemUser::where("user_id", $user_id)->find();
                
                if (! empty($post['user_id'])) {
                    
                    $data['update_time'] = date('Y-m-d H:i:s', time());
                    unset($post['password']);
                    unset($post['agencyId']);
                    
                    $save = SystemUser::where("user_id", $post['user_id'])->update($post);
                    
                    $id = $post['user_id'];
                } else {
                    $data['agency_id'] = $user_id;
                    
                    $data['create_time'] = time();
                    $data['password'] = md5($post['password']);
                    $save = $this->model->save($data);
                    $id = $this->model->id;
                }
                
                if (! empty($roleIds)) {
                    $insert = [];
                    
                    SystemUserRole::where("user_id", $id)->delete();
                    
                    foreach ($roleIds as $key => $value) {
                        $insert[] = array(
                            'role_id' => $value,
                            'user_id' => $id,
                            'tenant_id' => $data['tenant_id'],
                            'create_time' => time()
                        );
                    }
                    
                    if (! empty($insert)) {
                        SystemUserRole::insertAll($insert);
                    }
                }
                
                Db::commit();
                return empty($post['user_id']) ? msg([], 0, "新增成功") : msg([], 0, "修改成功");
            } catch (\Exception $e) {
                Db::rollback();
                return msg([], 1, "保存失败 " . $e->getMessage() . " line:" . $e->getLine());
            }
        }
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function del($id)
    {
        $row = $this->model->whereIn('user_id', $id)->select();
        if ($row->isEmpty()) {
            return msg([], 1, "数据不存在");
        }
        try {
            $save = Db::table('wjyk_system_user')->whereIn('user_id', $id)->delete();
        } catch (\Exception $e) {
            return msg([], 1, "删除异常" . $e->getMessage());
        }
        return $save ? msg([], 0, "删除成功") : msg([], 1, "删除失败");
    }

    /**
     * @NodeAnotation(title="变更用户状态")
     */
    public function status()
    {
        $request = $this->request;
        
        try {
            $user_id = input("user_id");
            $status = input("status");
            
            SystemUser::where("user_id", $user_id)->update([
                "status" => $status
            ]);
            
            return msg([], 0, "变更状态成功");
        } catch (\Throwable $th) {
            return msg([], 1, "获取数据失败 : " . $th->getMessage());
        }
    }

    /**
     * 添加更新商户
     * @NodeAnotation(title="添加更新商户")
     */
    public function reloadQrcode()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                require "../vendor/phpqrcode/phpqrcode.php";
                $user_id = $post['user_id'];
                $url = getDyQrcode($user_id, "");
                User::where("user_id", $user_id)->update([
                    "qrcode" => $url
                ]);
                return msg([], 0, "生成成功");
            } catch (\Exception $e) {
                return msg([], 1, "更新失败 " . $e->getMessage());
            }
        }
    }

    /**
     * 添加前验证
     * @NodeAnotation(title="")
     */
    public function existence()
    {
        $request = $this->request;
        try {
            $field = input("field");
            $value = input("value");
            
            $count = $this->model->where($field, $value)->count();
            if ($count > 0) {
                return msg([], 0, "账号已存在");
            }
            
            return msg([], 1, "可以新增");
        } catch (\Throwable $th) {
            return msg([], 1, "获取数据失败 : " . $th->getMessage());
        }
    }

    /**
     * 重置密码
     * @NodeAnotation(title="")
     */
    public function password()
    {
        $request = $this->request;
        try {
            $password = input("password");
            $userId = input("userId");
            $user = $this->model->where("user_id", $userId)->find();
            if (empty($user)) {
                return msg([], 1, "账号不存在");
            }
            $user->password = md5($password);
            $user->save();
            return msg([], 0, "重置成功");
        } catch (\Throwable $th) {
            return msg([], 1, "重置失败 : " . $th->getMessage());
        }
    }

    /**
     * 获取商户信息
     * @NodeAnotation(title="")
     */
    public function getUser()
    {
        $request = $this->request;
        $user_id = $this->request->_UID;
        
        try {
            $id = input("id");
            $user = $this->model->where("user_id", $id)
                ->field("*,create_time createTime")
                ->find();
            
            return msg($user, 0, "查询账号成功");
        } catch (\Throwable $th) {
            return msg([], 1, "获取数据失败 : " . $th->getMessage());
        }
    }

    /**
     * 获取管理员首页数据
     * @NodeAnotation(title="获取管理员首页数据")
     */
    public function getAdminProfileData()
    {
        $user_count = FigureUser::count();
        
        $user['user_count'] = $user_count;
        
        return msg($user, 0, "查询成功");
    }

    /**
     * 获取管理员首页数据
     * @NodeAnotation(title="获取管理员首页数据")
     */
    public function getAdminSaleData()
    {
        $request = $this->request;
        $param = $request->param();
        $where = [];
        if ($this->request->platform_id >0 ){
            $where[] = ['platform_id','=',$this->request->platform_id];
        }
        $orderModel = new WriteLog();
        $userModel = new \app\admin\model\User();
        // 总金额
        $totalAmount = $orderModel->where($where)->sum('total_amount');
        $payAmount = $orderModel->where($where)->sum('pay_amount');
        $waitSubsidyAmount = $orderModel->where($where)

            ->where('subsidy_status','in', [1,2])
            ->sum('subsidy_amount');
        $applySubsidyAmount = $orderModel->where($where)
            ->where(['subsidy_status' => 2])
            ->sum('subsidy_amount');
        $subsidyAmount = $orderModel->where($where)
            ->where(['subsidy_status' => 4])
            ->sum('subsidy_amount');
        $todayTime =  strtotime(date('Y-m-d', time()));

        $todayUserCount = $userModel->where($where)->where('create_time','>=',$todayTime)->count();

        $userCount = $userModel->where($where)->count();
        $yesterdayUserCount = $userModel->where($where)->where('create_time','>=',$todayTime-86400)
            ->where('create_time','<',$todayTime)->count();

        $moonTime =  strtotime(date('Y-m', time()));
        $moonUserCount = $userModel->where($where)->where('create_time','>=',$moonTime)->count();
        $ConsumerClaimLogModel = new \app\admin\model\ConsumerClaimLog();
        $claimCount = $ConsumerClaimLogModel
            ->where( 'status','in',[2,3])->count();
        $storeClaimCount = $ConsumerClaimLogModel->where(['type' => 2])
            ->where( 'status','in',[2,3])->count();
        $platformClaimCount = $ConsumerClaimLogModel->where(['type' => 1])
            ->where( 'status','in',[2,3])->count();
        $writeClaimCount = $ConsumerClaimLogModel->where(['status' => 3])->count();
        $activityModel = new Activity();
        $activityCount  = $activityModel->where($where)->count();
        $ticketModel = new Ticket();
        $ticketCount  = $ticketModel->where($where)->count();

        $couponModel = new Coupon();
        $couponCount  = $couponModel->where($where)->count();
        $storeModel = new Store();
        $storeCount  = $storeModel->where($where)->count();

        $streamLogModel  = new StreamLog();

        $amount  = $streamLogModel->where($where)->sum('order_amount');
        $systemAmount  = $streamLogModel->where($where)->sum('system_handling_fee');
        $platformAmount  = $streamLogModel->where($where)->sum('platform_handling_fee');
        $storeAmount  = $streamLogModel->where($where)->sum('actual_amount');



        $orderLogModel = new OrderLog();
        $totalPayAmount  = $orderLogModel->where($where)->sum('pay_amount');
        $totalOrderAmount  = $orderLogModel->where($where)->where(['buy_type' => 1])->sum('pay_amount');
        $totalConsumerAmount  = $orderLogModel->where($where)->where(['buy_type' => 2])->sum('pay_amount');
        $totalTicketrAmount  = $orderLogModel->where($where)->where(['buy_type' => 3])->sum('pay_amount');


        $couponOrderModel = new CouponOrder();
        $couponAmount  = $couponOrderModel->where($where)->where(['pay_status'=> 2])->sum('price');

        return msg([
            "total_amount" => $totalAmount,
            "pay_amount" => $payAmount,
            "wait_subsidy_amount" => $waitSubsidyAmount,
            "apply_subsidy_amount" => $applySubsidyAmount,
            "subsidy_amount" => $subsidyAmount,

            "user_count" => $userCount,
            "today_user_count" => $todayUserCount,
            "yesterday_user_count" => $yesterdayUserCount,
            "moon_user_count" => $moonUserCount,

            'platform_claim_count' => $platformClaimCount,
            'store_claim_count' => $storeClaimCount,
            'claim_count' => $claimCount,
             'write_claim_count'=> $writeClaimCount,

            'store_count' => $storeCount,
            'activity_count' => $activityCount,
            'coupon_count' => $couponCount,
            'ticket_count' => $ticketCount,

            'amount' => $amount,
            'system_amount' => $systemAmount,
            'platform_amount' => $platformAmount,
            'store_amount' => $storeAmount,


            'total_pay_amount' => $totalPayAmount,
            'total_order_amount' => $totalOrderAmount,
            'total_consumer_amount' => $totalConsumerAmount,
            'total_ticket_amount' => $totalTicketrAmount,
            'coupon_amount' => $couponAmount,




        ], 0, "查询成功");

    }







}